//
//  AddressManagerViewController.m
//  体育商城
//
//  Created by  on 2022/9/24.
//

#import "AddressManagerViewController.h"
#import "AddressCell.h"
#import "AddAddressViewController.h"

@interface AddressManagerViewController ()
@property (strong, nonatomic) UIButton *rightBtn;
@property (strong, nonatomic) IBOutlet UIView *toolBar;
@property (strong, nonatomic) IBOutlet UIButton *selectAll;
@property (nonatomic, strong) NSArray <Address *>*array;
@end

@implementation AddressManagerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
    [self loadData];
}
- (void)initUI{
    self.title = LS(@"我的收货地址");
    self.rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.rightBtn.tag = 204;
    self.rightBtn.frame = CGRectMake(0, StuBarHight + 5, 60, 34);
    [self.rightBtn addTarget:self action:@selector(actionForBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.rightBtn setTitleColor:[UIColor colorHex:@"#1A1A1A"] forState:UIControlStateNormal];
    [self.rightBtn setTitle:LS(@"管理") forState:UIControlStateNormal];
    [self.rightBtn setTitle:LS(@"完成") forState:UIControlStateSelected];
    if (self.block) {
        self.rightBtn.selected = YES;
    }
    UIBarButtonItem *item =[[UIBarButtonItem alloc] initWithCustomView:self.rightBtn];
    self.navigationItem.rightBarButtonItem = item;
    
    self.tableViewStyle = UITableViewStylePlain;
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.tableView registerNib:[AddressCell nib] forCellReuseIdentifier:[AddressCell ID]];
    NSLayoutConstraint *top = [self.tableView a1:NSLayoutAttributeTop e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeTop c: 0];
    NSLayoutConstraint *left = [self.tableView a1:NSLayoutAttributeLeft e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeLeft c:15];
    NSLayoutConstraint *right = [self.tableView a1:NSLayoutAttributeRight e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeRight c:-15];
    NSLayoutConstraint *bottom = [self.tableView a1:NSLayoutAttributeBottom e:NSLayoutRelationEqual t:self.toolBar a2:NSLayoutAttributeTop c:0];
    [self.view addConstraints:@[top,left,right,bottom]];
}
- (void)loadData{
    [AddressTool find:APP.user.account complete:^(NSArray * _Nonnull result) {
        self.array = result;
    }];
}
- (void)updateData:(BOOL)selected index:(NSInteger)index{
    int num = 0;
    for (int i = 0; i<self.array.count; i++) {
        Address *model = self.array[i];
        
        if (self.array.count < index) {
            if (self.selectAddress && self.selectAddress.ID == model.ID) {
                model.selected = self.selectAddress.selected;
            }else{
                model.selected = selected;
            }
        }else{
            if (self.block) {
                model.selected = index == i;
                if (index == i) {
                    self.selectAddress = model;
                }
            }else{
                if (i == index) { model.selected = !model.selected;}
                num = model.selected ? num+1:num;
            }
        }
    }
    if (self.array.count > index) {
        self.selectAll.selected = self.array.count == num || (num > 0 && self.selectAll.selected);
    }
    [self.tableView reloadData];
}
- (void)setArray:(NSArray<Address *> *)array{
    _array = array;
    [self updateData:NO index:self.array.count + 1];
}
- (void)backBtnAction{
    if (self.navigationController.viewControllers.count > 1) {
        [super backBtnAction];
    }else{
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
- (IBAction)actionForBtn:(UIButton *)sender {
    if (APP.user.account ==  nil || APP.user.account.length <= 0) {
        return [Toast msg:LS(@"您还未登录，请先去登录")];
    }
    
    switch (sender.tag){
        case 201:///全选
            sender.selected = !sender.selected;
            [self updateData:sender.selected index:self.array.count+1];
            break;
        case 202:///删除
        {
            self.selectAll.selected = NO;
            NSMutableArray *array = [NSMutableArray array];
            for (Address *m in self.array) {
                if (m.selected == NO) { [array addObject:m]; }
                [AddressTool delete:m complete:nil];
            }
            self.array = array;
        }
            break;
        case 203:///添加收货人地址
        {   AddAddressViewController *vc = [AddAddressViewController new];
            vc.account = (int)self.array.count;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 204:///管理/完成
            if (self.block) {
                if (self.selectAddress == nil) {
                    return [Toast msg:LS(@"请选择一个地址")];
                }
                self.block(self.selectAddress);
                return [self backBtnAction];
            }
            self.selectAll.selected = NO;
            sender.selected = !sender.selected;
            self.toolBar.hidden = !sender.selected;
            [self updateData:NO index:self.array.count+1];
            break;
        default:
            break;
    }
}
#pragma mark - 通知
- (void)addNotify{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:notifyAddressUpdate object:nil];
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.array.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    AddressCell *cell = [tableView dequeueReusableCellWithIdentifier:[AddressCell ID]];
    Address *model = self.array[indexPath.section];
    cell.model = model;
    cell.selectBtnLeft.constant = self.rightBtn.selected || self.block? 10 : -20;
    WS(self)
    cell.block = ^{
        [weakself updateData:NO index:indexPath.section];
    };
    return cell;
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    AddAddressViewController *vc = [AddAddressViewController new];
    vc.model = self.array[indexPath.section];
    vc.account = (int)self.array.count;
    [self.navigationController pushViewController:vc animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return section == self.array.count - 1 ? 20 : 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor clearColor];
    return view;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == self.array.count - 1){
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor clearColor];
        return view;
    }else{
        return nil;
    }
}

@end
